<template>
  <div class="svg-editor-container" @mousedown="documentClickEvent">
    <!-- 左侧工具栏 -->
    <div class="toolbar-left">
      <el-card class="toolbar-card" shadow="hover">
        <n-message-provider>
          <left-tool-bar
            :left_imglists="leftimg_lists"
            :select_toolbar="select_toolbar"
            @setCreatSvgInfo="setCreatSvgInfo"
          ></left-tool-bar>
        </n-message-provider>
      </el-card>
    </div>

    <!-- 中间画布区域 -->
    <div
      class="canvas-wrapper"
      @drop="dropEvent"
      @dragenter="dragEnterEvent"
      @dragover="dragOverEvent"
      @mousemove="mouseMoveEvent"
      @mouseup="mouseUpEvent"
      @mouseleave="handleMouseLeave"
      @mousedown.stop="mouseDownCanvasEvent"
    >
      <div class="canvas-container">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          :style="'background-color:' + props.tBackgroundColor"
          :width="svgCanvas.width"
          :height="svgCanvas.height"
          :viewBox="`0 0 ${svgCanvas.width} ${svgCanvas.height}`"
          ref="svg_dom_ref"
          class="canvas-svg"
        >
          <defs />
          <filter x="0" y="0" width="1" height="1" id="solid">
            <feFlood flood-color="rgb(255,255,255)" />
            <feComposite in="SourceGraphic" />
          </filter>
          <g
            v-for="(item, index) in svgLists"
            :class="
              item.id == select_svg.id ||
              select_svg_list.filter((e) => e.id === item.id).length > 0
                ? 'svg-selected'
                : ''
            "
            :key="item.id"
            :id="item.id"
            :transform="
              'translate(' +
              item.svgPositionX +
              ',' +
              item.svgPositionY +
              ')' +
              'rotate(' +
              item.angle +
              ')' +
              'scale(' +
              item.size +
              ')'
            "
            @mousedown.stop="mouseDownEvent(item, index, $event)"
            @click="svgClickHandel"
            @contextmenu.stop="contextmenuEvent"
          >
            <svg-dynamic
              :component_type="item.type"
              :component_template="
                props.component_infos.filter((f) => f.type == item.type)[0]
                  .template
              "
              :component_props="
                props.component_infos.filter((f) => f.type == item.type)[0].props
              "
              :component_attr="item"
            />
          </g>
          <!-- 选择框 -->
          <rect
            v-if="isSelecting && selectionBox.width > 0 && selectionBox.height > 0"
            :x="selectionBox.x"
            :y="selectionBox.y"
            :width="selectionBox.width"
            :height="selectionBox.height"
            fill="rgba(64, 158, 255, 0.1)"
            stroke="#409eff"
            stroke-width="2"
            stroke-dasharray="5,5"
            pointer-events="none"
          />
        </svg>
      </div>
    </div>

    <!-- 右侧属性面板 -->
    <el-drawer
      v-model="rightnav_open"
      :direction="'rtl'"
      :size="350"
      class="property-drawer"
      title="属性设置"
      :with-header="true"
    >
      <right-tool-bar :set_svg_info="set_svg_info"></right-tool-bar>
    </el-drawer>

    <!-- 右键菜单 -->
    <el-card v-show="display_contextmenu" ref="contextMenuRef" class="contextMenu" shadow="always">
      <template #default>
        <div
          v-for="(item, index) in contextmenu_data"
          :key="index"
          @click="item.fun()"
        >
          <div class="context-menu-item" :class="item.enable ? '' : 'disabled'">
            <span class="menu-name">{{ item.name }}</span>
            <span class="menu-shortcut">{{ item.hotkey }}</span>
          </div>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, Ref, ref, watch } from "vue";
import fp from "./Dialog/fanParameters.vue";
import TopToolBar from "./TopBar.vue";
import LeftToolBar from "./LeftToolBar.vue";
import RightToolBar from "./RightToolBar.vue";
import BottomBar from "./BottomBar.vue";
import { c, NMessageProvider } from "naive-ui";
import {
  IComponentInfo,
  ISvgDataLists,
  ISvgCanvas,
  ILeftImgLists,
  IMouseInfo,
  ISelectSvg,
} from "../Model";
import SvgDynamic from "./SvgDynamic.vue";
import { useMessage } from "naive-ui";
import "../assets/css/svgAnimation/index.css";
import {
  moveUp,
  moveDown,
  moveLeft,
  moveRight,
  hotkeyCopy,
  hotkeyDel,
  hotkeyPutOnTop,
  hotkeyPutOnButtom,
  hotkeyPutOnUp,
  hotkeyPutOnDown,
} from "../func/HotkeyFunc";
const emit = defineEmits(["saveSvgInfo", "loadExample"]);
const message = useMessage();

const props = defineProps({
  //组件的json格式
  component_infos: {
    type: Array as () => Array<IComponentInfo>,
    required: true,
    default: [],
  },
  svgCanvas: {
    type: Object as () => ISvgCanvas,
    default: { width: 1520, height: 720 },
  },
  tBackgroundColor: {
    type: String,
    default: "#000000",
  },
});

const svg_dom_ref = ref<null | HTMLElement>(null);
const contextMenuRef = ref<any>();
const svgLists: ISvgDataLists[] = reactive([]);
const topbar_dom_ref = ref(null);
let select_svg_list: ISvgDataLists[] = reactive([]); //鼠标框选所有的被选中svg列表
const loadExample = (path, name) => {
  emit("loadExample", path, name);
};
const mouseRect: ISvgDataLists = reactive({
  //鼠标框选矩形
  id: `mouseRect`,
  nodeKey: "mouseRect",
  type: "RectSvg",
  active_type: "",
  title: "鼠标框选矩形",
  svgPositionX: 0,
  svgPositionY: 0,
  angle: 0,
  size: 1,
  extend_attr: JSON.parse(
    JSON.stringify({
      color: { title: "边框颜色", val: "#FF0000", type: "colorinputbox" },
      fillcolor: {
        title: "填充颜色",
        val: "#FFFFFF00",
        type: "colorinputbox",
      },
      wh: {
        width: 0,
        height: 0,
      },
      stroke: {
        width: 2,
      },
    })
  ),
  active: "",
  create_type: "draggable",
});
//显示右键菜单
const display_contextmenu = ref(false);
//右键菜单数据
const contextmenu_data = reactive([
  {
    name: "复制",
    hotkey: "Ctrl+c",
    enable: true,
    fun: function () {
      if (!this.enable) {
        return;
      }
      hotkeyCopy(svgLists, select_svg, select_svg_list);
      display_contextmenu.value = false;
    },
  },
  {
    name: "删除",
    hotkey: "Delete",
    enable: false,
    fun: function () {
      if (!this.enable) {
        return;
      }
      hotkeyDel(svgLists, select_svg, select_svg_list);
      display_contextmenu.value = false;
    },
  },
  {
    name: "置于顶层",
    hotkey: "Ctrl+→",
    enable: true,
    fun: function () {
      if (!this.enable) {
        return;
      }
      hotkeyPutOnTop(svgLists, select_svg);
      display_contextmenu.value = false;
    },
  },
  {
    name: "置于底层",
    hotkey: "Ctrl+←",
    enable: true,
    fun: function () {
      if (!this.enable) {
        return;
      }
      hotkeyPutOnButtom(svgLists, select_svg);
      display_contextmenu.value = false;
    },
  },
  {
    name: "置于上一层",
    hotkey: "Ctrl+↑",
    enable: true,
    fun: function () {
      if (!this.enable) {
        return;
      }
      hotkeyPutOnUp(svgLists, select_svg);
      display_contextmenu.value = false;
    },
  },
  {
    name: "置于下一层",
    hotkey: "Ctrl+↓",
    enable: true,
    fun: function () {
      if (!this.enable) {
        return;
      }
      hotkeyPutOnDown(svgLists, select_svg);
      display_contextmenu.value = false;
    },
  },
]);
const set_svg_info: Ref<ISvgDataLists> = ref({
  id: "",
  nodeKey: "",
  title: "",
  svgPositionX: 0,
  svgPositionY: 0,
});
//选中的svg
let select_svg: ISelectSvg = reactive({
  id: "",
  nodeKey: "",
  index: 0,
  sPositionX: 0,
  sPositionY: 0,
  create_type: "",
});
//选中的左侧工具栏的svg
const select_lefttool: Ref<IComponentInfo> = ref({});
//左侧工具栏svg列表
const leftimg_lists: Ref<ILeftImgLists> = ref({
  textComponentList: [],
  commonComponentList: [],
  powerComponentList: [], //电力组件
  drawComponentList: [],
  chartComponentList: [],
  waterComponentList: [], //水务组件
  coalComponentList: [], //水务组件
});
//选中的左侧工具栏
const select_toolbar: Ref<string | undefined> = ref("");
//记录鼠标信息
const mouseInfo: IMouseInfo = reactive({
  status: 0,
  mPositionX: 0,
  mPositionY: 0,
});
const drawRectFlag = ref(false);
const svgClickHandel = () => {};
const rightnav_open = ref(false);
// 框选状态
const isSelecting = ref(false);
const selectionBox = reactive({
  x: 0,
  y: 0,
  width: 0,
  height: 0,
  startX: 0,
  startY: 0
});
/**
 * @description: 从左侧工具栏拖动组件到画布触发的事件
 * @param {*}
 * @return {*}
 */
const dropEvent = (e: DragEvent) => {
  //当左侧工具栏拖动到此处时在画布上创建该组件
  if (Object.keys(select_lefttool.value).length < 1) {
    //未选择任何组件
    return;
  }
  //在鼠标位置创建当前组件
  const create_svg: ISvgDataLists = {
    id: `${new Date().getTime()}` + Math.ceil(Math.random() * 100),
    nodeKey: "",
    type: select_lefttool.value.type,
    active_type: select_lefttool.value.active_type,
    title: select_lefttool.value.title,
    svgPositionX: e.offsetX,
    svgPositionY: e.offsetY,
    angle: 0,
    size: 1,
    extend_attr: select_lefttool.value.extend_attr
      ? JSON.parse(JSON.stringify(select_lefttool.value.extend_attr))
      : "",
    active: select_lefttool.value.active
      ? JSON.parse(JSON.stringify(select_lefttool.value.active))
      : "",
    click_event: select_lefttool.value.click_event
      ? JSON.parse(JSON.stringify(select_lefttool.value.click_event))
      : "",
  };
  svgLists.push(create_svg);
  //清空左侧工具选中
  select_lefttool.value = {};
};
const dragEnterEvent = (e: DragEvent) => {
  //dragenter和dragover一定要阻止浏览器默认行为 不然不会触发drop
  rightnav_open.value = false;
  e.preventDefault();
};
const dragOverEvent = (e: DragEvent) => {
  //dragenter和dragover一定要阻止浏览器默认行为 不然不会触发drop
  e.preventDefault();
};
/**
 * @description: 设置要创建组件的信息
 * @param {*} createsvg_info 选中的组件信息
 * @return {*}
 */
const setCreatSvgInfo = (createsvg_info: IComponentInfo) => {
  select_lefttool.value = createsvg_info;
  select_toolbar.value = createsvg_info.type;
};
/**
 * @description: 保存绘制组件后的数据和svgdom
 * @param {*}
 * @return {*}
 */
const saveSvgInfo = () => {
  // if (svgLists.length == 0) {
  //   (topbar_dom_ref.value as any).saveSvgInfoRes({ code: 2, msg: '请先绘制图像!' });
  //   return;
  // }
  // (topbar_dom_ref.value as any).saveSvgInfoRes(svgLists.length > 0 ? { code: 1, msg: '保存成功!' } : { code: 0, msg: '保存失败!' });
  // emit('saveSvgInfo', svgLists, svg_dom_ref.value)

  if (svgLists.length == 0) {
    message.error("请先绘制图像!");
    return;
  }
  emit("saveSvgInfo", svgLists, svg_dom_ref.value);
  message.success("保存成功!");
};

const clearSelection = () => {
  isSelecting.value = false;
  selectionBox.x = 0;
  selectionBox.y = 0;
  selectionBox.width = 0;
  selectionBox.height = 0;
  drawRectFlag.value = false;
  select_svg_list.length = 0; // 框选消失的时候清除select列表
  select_svg.id = ""; // 清除选中状态
};

/**
 * @description: 鼠标点击画布
 * @param {*}
 * @return {*}
 */
const mouseDownCanvasEvent = (e: MouseEvent) => {
  console.log('🔴 mouseDownCanvasEvent 点击画布，select_lefttool:', Object.keys(select_lefttool.value).length);
  
  //判断当前是否有选中的工具栏
  if (Object.keys(select_lefttool.value).length < 1) {
    rightnav_open.value = false;
    clearSelection(); // 清除之前的框选
    
    // 只记录鼠标位置，不开始框选
    mouseInfo.mPositionX = e.offsetX;
    mouseInfo.mPositionY = e.offsetY;
    selectionBox.startX = e.offsetX;
    selectionBox.startY = e.offsetY;
    mouseInfo.status = 1;
    
    // 不设置 isSelecting，等待 mouseMove 判断是否超过 5px
    isSelecting.value = false;
    console.log('🔴 记录鼠标位置，等待移动');
    
    return;
  }
  //在当前位置创建要绘制的组件
  const create_svg: ISvgDataLists = {
    id: `${new Date().getTime()}` + Math.ceil(Math.random() * 100),
    nodeKey: "",
    type: select_lefttool.value.type,
    title: select_lefttool.value.title,
    svgPositionX: e.offsetX,
    svgPositionY: e.offsetY,
    angle: 0,
    size: 1,
    extend_attr: JSON.parse(JSON.stringify(select_lefttool.value.extend_attr)), //这个响应式对象我治不了了 所以只能写两次转换
    active: JSON.parse(JSON.stringify(select_lefttool.value.active)), //这个响应式对象我治不了了 所以只能写两次转换
  };
  svgLists.push(create_svg);
  //设置全局选中的组件信息
  ({
    id: select_svg.id,
    nodeKey: select_svg.nodeKey,
    svgPositionX: select_svg.sPositionX,
    svgPositionY: select_svg.sPositionY,
  } = create_svg);
  rightnav_open.value = false;
  select_svg.index = svgLists.length - 1;
  select_svg.create_type = "draw";
  mouseInfo.status = 1;
  mouseInfo.mPositionX = e.clientX;
  mouseInfo.mPositionY = e.clientY;
};
/**
 * @description: 鼠标点击画布上svg触发事件
 * @param {*}
 * @return {*}
 */
const mouseDownEvent = (
  selectsvg: ISvgDataLists,
  index: number,
  e: MouseEvent
) => {
  // 右键点击时，不要阻止事件冒泡，让 contextmenu 事件正常触发
  if (e.button === 2) {
    // 右键点击，清除工具栏选中即可
    select_lefttool.value = {};
    return;
  }
  
  e.preventDefault();
  e.stopPropagation(); // 使用 stopPropagation 代替 cancelBubble
  
  //清空左侧工具选中
  select_lefttool.value = {};
  
  // 判断是否点击了框选中的组件
  const isInSelection = select_svg_list.some(item => item.id === selectsvg.id);
  
  if (isInSelection && select_svg.id === "mouseRect") {
    // 点击了框选中的组件，保持框选状态，准备移动所有框选组件
    console.log('🔵 点击框选中的组件，准备移动');
    select_svg.id = "mouseRect";
  } else {
    // 点击了非框选中的组件，清除框选，准备拖动单个组件
    console.log('🟢 点击非框选中的组件，准备拖动单个组件');
    if (select_svg.id !== "mouseRect") clearSelection();
    
    //鼠标在画布上的组件按下记录选中的组件信息和鼠标位置信息等
    ({
      id: select_svg.id,
      nodeKey: select_svg.nodeKey,
      svgPositionX: select_svg.sPositionX,
      svgPositionY: select_svg.sPositionY,
    } = selectsvg);
    
    select_svg.index = index;
  }
  
  rightnav_open.value = false;
  select_svg.create_type = "draggable";
  mouseInfo.status = 1;
  mouseInfo.mPositionX = e.clientX;
  mouseInfo.mPositionY = e.clientY;
};
const mouseMoveEvent = (e: MouseEvent) => {
  if (mouseInfo.status === 1) {
    //鼠标按下状态
    
    // 如果正在框选，更新选择框
    if (isSelecting.value) {
      console.log('🔵 正在框选，更新选择框');
      const startX = Math.min(e.offsetX, selectionBox.startX);
      const startY = Math.min(e.offsetY, selectionBox.startY);
      const endX = Math.max(e.offsetX, selectionBox.startX);
      const endY = Math.max(e.offsetY, selectionBox.startY);
      
      selectionBox.x = startX;
      selectionBox.y = startY;
      selectionBox.width = endX - startX;
      selectionBox.height = endY - startY;
      return;
    }
    
    // 不是框选状态，判断是否需要开始框选
    if (select_svg.id === "" && !select_lefttool.value.type && !isSelecting.value) {
      const moveX = Math.abs(e.offsetX - mouseInfo.mPositionX);
      const moveY = Math.abs(e.offsetY - mouseInfo.mPositionY);
      console.log('🟢 检查是否需要开始框选, moveX:', moveX, 'moveY:', moveY);
      if (moveX > 5 || moveY > 5) {
        // 移动超过5px，开始框选
        console.log('🟢 开始框选！');
        isSelecting.value = true;
        drawRectFlag.value = true;
        selectionBox.startX = mouseInfo.mPositionX;
        selectionBox.startY = mouseInfo.mPositionY;
        selectionBox.x = mouseInfo.mPositionX;
        selectionBox.y = mouseInfo.mPositionY;
        selectionBox.width = 0;
        selectionBox.height = 0;
      }
      return;
    }
    
    // 拖动组件逻辑
    if (select_svg.id === "") {
      return;
    }
    
    const { clientX, clientY } = e;
    
    // 如果是框选模式（点击了框选中的组件），移动所有框选的组件
    if (select_svg.id === "mouseRect" && select_svg_list.length > 0) {
      console.log('🔵 框选模式下移动所有组件');
      const deltaX = clientX - mouseInfo.mPositionX;
      const deltaY = clientY - mouseInfo.mPositionY;
      
      // 移动所有框选的组件
      for (const item of select_svg_list) {
        item.svgPositionX += deltaX;
        item.svgPositionY += deltaY;
      }
      
      // 更新鼠标位置
      mouseInfo.mPositionX = clientX;
      mouseInfo.mPositionY = clientY;
      return;
    }
    
    // 单个组件的拖动
    if (select_svg.create_type == "draggable") {
      let new_select_svg = { ...select_svg };
      new_select_svg.sPositionX += clientX - mouseInfo.mPositionX;
      new_select_svg.sPositionY += clientY - mouseInfo.mPositionY;
      //更新视图
      ({
        nodeKey: svgLists[select_svg.index].nodeKey,
        sPositionX: svgLists[select_svg.index].svgPositionX,
        sPositionY: svgLists[select_svg.index].svgPositionY,
      } = new_select_svg);
    } else if (select_svg.create_type == "draw") {
      //拓展属性里未配置的属性不进行赋值
      if (svgLists[select_svg.index].extend_attr?.startpoint_x?.val != null) {
        svgLists[select_svg.index].extend_attr.startpoint_x.val = 0;
      }
      if (svgLists[select_svg.index].extend_attr?.startpoint_y?.val != null) {
        svgLists[select_svg.index].extend_attr.startpoint_y.val = 0;
      }
      if (svgLists[select_svg.index].extend_attr?.endpoint_x?.val != null) {
        svgLists[select_svg.index].extend_attr.endpoint_x.val =
          clientX - mouseInfo.mPositionX;
      }
      if (svgLists[select_svg.index].extend_attr?.endpoint_y?.val != null) {
        svgLists[select_svg.index].extend_attr.endpoint_y.val =
          clientY - mouseInfo.mPositionY;
      }
    }
  }
};
const mouseUpEvent = (e: MouseEvent) => {
  console.log('🟡 mouseUpEvent, isSelecting:', isSelecting.value, 'select_svg.id:', select_svg.id);
  
  if (isSelecting.value) {
    // 框选结束（这是在空白区域拖动）
    console.log('🟡 结束框选（从空白区域拖动）');
    isSelecting.value = false;
    drawRectFlag.value = false;
    
    // 清空之前的框选列表
    select_svg_list.length = 0;
    
    const startX = Math.min(selectionBox.startX, e.offsetX);
    const startY = Math.min(selectionBox.startY, e.offsetY);
    const endX = Math.max(selectionBox.startX, e.offsetX);
    const endY = Math.max(selectionBox.startY, e.offsetY);
    
    // 遍历所有svg 找到所有在框选范围的组件
    for (const item of svgLists) {
      // 检查组件是否在框选范围内
      if (
        item.svgPositionX >= startX &&
        item.svgPositionX <= endX &&
        item.svgPositionY >= startY &&
        item.svgPositionY <= endY
      ) {
        select_svg_list.push(item);
      }
    }
    
    console.log('🟡 选中组件数量:', select_svg_list.length);
    
    // 如果有选中的组件，设置为框选模式
    if (select_svg_list.length > 0) {
      select_svg.id = "mouseRect";
    } else {
      // 没有选中任何组件，清除框选
      select_svg.id = "";
    }
    
    // 清空选择框显示
    selectionBox.width = 0;
    selectionBox.height = 0;
    
    mouseInfo.status = 0;
    return;
  }
  //如果鼠标不是按下状态或者没有选择组件
  console.log('🟡 mouseUpEvent 继续执行, status:', mouseInfo.status, 'select_svg.id:', select_svg.id);
  
  // 如果没有点击组件，也是正常的情况
  if (mouseInfo.status != 1) {
    console.log('🟡 鼠标状态不是按下，直接返回');
    mouseInfo.status = 0;
    return;
  }
  
  if (!select_svg.id) {
    console.log('🟡 没有选中组件，结束鼠标状态');
    mouseInfo.status = 0;
    return;
  }
  if (select_svg.id === "mouseRect") {
    console.log('🟡 移动框选组件');
    let x = mouseInfo.mPositionX;
    let y = mouseInfo.mPositionY;
    for (const s of select_svg_list) {
      s.svgPositionX = s.svgPositionX + (e.clientX - x);
      s.svgPositionY = s.svgPositionY + (e.clientY - y);
    }
  }
  mouseInfo.status = 0;
  
  // 计算鼠标移动距离，判断是点击还是拖动
  const moveX = Math.abs(e.clientX - mouseInfo.mPositionX);
  const moveY = Math.abs(e.clientY - mouseInfo.mPositionY);
  const moved = moveX > 3 || moveY > 3; // 移动超过3px认为是拖动
  
  // 点击了单个组件（未拖动）
  if (!moved && select_svg.id && select_svg.id !== "mouseRect") {
    // 获取最新选中的组件信息
    const selectedItem = svgLists.find(item => item.id === select_svg.id);
    if (selectedItem) {
      set_svg_info.value = selectedItem;
    } else {
      set_svg_info.value = svgLists[select_svg.index];
    }
    rightnav_open.value = true;
  }
  
  // 点击了空白处（未拖动），清除框选
  if (!moved && !select_svg.id && !isSelecting.value) {
    clearSelection();
  }
  
  //清空左侧工具选中
  select_lefttool.value = {};
  select_toolbar.value = "";
};

/**
 * @description: 鼠标右键
 * @param {*}
 * @return {*}
 */
const contextmenuEvent = (e: MouseEvent) => {
  e.preventDefault();
  display_contextmenu.value = true;
  if (contextMenuRef.value) {
    const menuElement = contextMenuRef.value.$el;
    if (menuElement) {
      menuElement.style.left = e.pageX + "px";
      menuElement.style.top = e.pageY + "px";
      menuElement.style.position = "absolute";
    }
  }
  contextmenu_data.map((m) => (m.enable = true));
  //判断当前选中组件的index
  if (svgLists.length === 1) {
    //禁用下移
    contextmenu_data[3].enable = false;
    contextmenu_data[5].enable = false;
    //禁用上移
    contextmenu_data[2].enable = false;
    contextmenu_data[4].enable = false;
  } else if (select_svg.index === 0) {
    //禁用下移
    contextmenu_data[3].enable = false;
    contextmenu_data[5].enable = false;
  } else if (select_svg.index === svgLists.length - 1) {
    //禁用上移
    contextmenu_data[2].enable = false;
    contextmenu_data[4].enable = false;
  }
};

/**
 * @description: 点击页面其他位置隐藏右键菜单
 * @param {*}
 * @return {*}
 */
const documentClickEvent = (e: MouseEvent) => {
  // 点击左键时隐藏右键菜单
  if (e.button === 0) {
    // 延迟隐藏，避免与右键菜单显示冲突
    setTimeout(() => {
      display_contextmenu.value = false;
    }, 100);
  }
};

const handleMouseLeave = () => {
  // 鼠标移出画布时，如果正在框选，结束框选
  if (isSelecting.value) {
    isSelecting.value = false;
    drawRectFlag.value = false;
    selectionBox.width = 0;
    selectionBox.height = 0;
    mouseInfo.status = 0;
  }
};
watch(
  () => [...props.component_infos],
  (newval, oldval) => {
    leftimg_lists.value = {
      textComponentList: newval.filter((f) => f.panel_class == "text"),
      commonComponentList: newval.filter((f) => f.panel_class == "common"),
      powerComponentList: newval.filter((f) => f.panel_class == "power"),
      drawComponentList: newval.filter((f) => f.panel_class == "draw"),
      chartComponentList: newval.filter((f) => f.panel_class == "chart"),
      waterComponentList: newval.filter((f) => f.panel_class == "water"),
      coalComponentList: newval.filter((f) => f.panel_class == "coal"),
    };
  }
);
//监听键盘
document.onkeyup = (e) => {
  console.log("键盘监听", e, select_svg);
  //如果没选中组件
  if (!select_svg.id) {
    return;
  }
  if (!e.ctrlKey && e.key == "ArrowUp") {
    e.preventDefault();
    moveUp(svgLists, select_svg);
  } else if (!e.ctrlKey && e.key == "ArrowDown") {
    e.preventDefault();
    moveDown(svgLists, select_svg);
  } else if (!e.ctrlKey && e.key == "ArrowLeft") {
    e.preventDefault();
    moveLeft(svgLists, select_svg);
  } else if (!e.ctrlKey && e.key == "ArrowRight") {
    e.preventDefault();
    moveRight(svgLists, select_svg);
  }
  //ctrl  c
  else if (e.ctrlKey && e.key.toLowerCase() == "c") {
    e.preventDefault();
    hotkeyCopy(svgLists, select_svg, select_svg_list);
    if (select_svg.id === "mouseRect" || select_svg_list.length) {
      //鼠标框选存在
      mouseRect.svgPositionX += 100;
      mouseRect.svgPositionY += 50;
    }
  }
  //deleted
  else if (e.key == "Delete") {
    e.preventDefault();
    hotkeyDel(svgLists, select_svg, select_svg_list);
    rightnav_open.value = false;
  }
  //上移一层
  else if (e.ctrlKey && e.key == "ArrowUp") {
    e.preventDefault();
    hotkeyPutOnUp(svgLists, select_svg);
  }
  //下移一层
  else if (e.ctrlKey && e.key == "ArrowDown") {
    e.preventDefault();
    hotkeyPutOnDown(svgLists, select_svg);
  }
  //置于底层
  else if (e.ctrlKey && e.key == "ArrowLeft") {
    e.preventDefault();
    hotkeyPutOnButtom(svgLists, select_svg);
  }
  //置于顶层
  else if (e.ctrlKey && e.key == "ArrowRight") {
    e.preventDefault();
    hotkeyPutOnTop(svgLists, select_svg);
  }
};
const setSvgLists = (new_val: ISvgDataLists[]) => {
  console.log(new_val);
  svgLists.length = 0;
  svgLists.push(...new_val);
  emit("saveSvgInfo", svgLists, svg_dom_ref.value);
};
defineExpose({
  setSvgLists,
  saveSvgInfo,
});
</script>

<style lang="scss" scoped>
.svg-editor-container {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  overflow: hidden;
}

.toolbar-left {
  width: 220px;
  height: 100%;
  padding: 12px;
  
  .toolbar-card {
    height: 100%;
    border-radius: 8px;
    overflow: hidden;
    
    :deep(.el-card__body) {
      padding: 12px;
      height: 100%;
    }
  }
}

.canvas-wrapper {
  flex: 1;
  height: 100%;
  padding: 12px;
  overflow: hidden;
  
  &::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    
    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }
}

.canvas-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 8px;
  transition: all 0.3s ease;
  overflow: auto;
  
  &::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    
    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }
  
  &:hover {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
  }
}

.canvas-svg {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.contextMenu {
  position: absolute !important;
  z-index: 99999;
  min-width: 200px;
  padding: 8px 0;
  
  :deep(.el-card__body) {
    padding: 0;
  }
  
  .context-menu-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 16px;
    cursor: pointer;
    transition: all 0.2s ease;
    user-select: none;
    
    &:hover {
      background-color: #409eff;
      color: #ffffff;
    }
    
    &.disabled {
      color: #c0c4cc;
      cursor: not-allowed;
      
      &:hover {
        background-color: transparent;
        color: #c0c4cc;
      }
    }
    
    .menu-name {
      font-size: 14px;
    }
    
    .menu-shortcut {
      font-size: 12px;
      color: #909399;
      margin-left: 12px;
    }
  }
  
  .context-menu-item:hover .menu-shortcut {
    color: rgba(255, 255, 255, 0.9);
  }
}

.property-drawer {
  :deep(.el-drawer__header) {
    margin-bottom: 20px;
    padding: 20px;
    border-bottom: 1px solid #e4e7ed;
  }
  
  :deep(.el-drawer__body) {
    padding: 20px;
  }
}

.svg-selected {
  outline: 2px solid #409eff;
  outline-offset: 2px;
  filter: drop-shadow(0 0 4px rgba(64, 158, 255, 0.3));
}

@media (max-width: 1200px) {
  .toolbar-left {
    width: 180px;
  }
}
</style>
